import pygame, math, os

from tile import Tile
from player import Player
from hex import Hex
from game import Game

WIDTH = 1200
HEIGHT = 600
CAPTION = 'Suburbia'
HEX_RADIUS = 30
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
HEX_X_START = 200
HEX_Y_START = 200

pygame.init()

size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)

pygame.display.set_caption(CAPTION)

font = pygame.font.Font(None, 36)

game = Game()
name1 = 'Player 1'
name2 = 'Player 2'
player1 = Player(name1, game, False)
player2 = Player(name2, game, False)
players = [player1, player2]

isEnd = 0

images = {}
for file in os.listdir('tiles'):
    if not file.startswith('.'):
        name = str(file)
        img = pygame.image.load(os.path.join('tiles', name)).convert()
        transparent = img.get_at((0,0))
        img.set_colorkey(transparent)
        images[name] = img

done = False

bigImg = None

def drawPlayerInfo(player):
    text = font.render(player.getName(), 1, BLACK)
    textpos = text.get_rect(centerx=WIDTH/2)
    screen.blit(text, textpos)
    
    money = font.render('Money: ' + str(player.getMoney()), 1, BLACK)
    moneypos = money.get_rect(centerx=100, centery=50)
    screen.blit(money, moneypos)
    
    income = font.render('Income: ' + str(player.getIncome()), 1, BLACK)
    incomepos = money.get_rect(centerx=100, centery=100)
    screen.blit(income, incomepos)
    
    population = font.render('Population: ' + str(player.getPopulation()), 1, BLACK)
    populationpos = population.get_rect(centerx=650, centery=50)
    screen.blit(population, populationpos)
    
    reputation = font.render('Reputation: ' + str(player.getReputation()), 1, BLACK)
    reputationpos = reputation.get_rect(centerx=650, centery=100)
    screen.blit(reputation, reputationpos)
    
def drawHex(x, y, radius, image, color):
    pointList = []
    for z in range(6):
        pointX = x + math.cos(z * 1.0472) * radius
        pointY = y + math.sin(z * 1.0472) * radius
        pointList.append((pointX, pointY))
    if (image == ''):
        pygame.draw.polygon(screen, color, pointList, 0) 
        pygame.draw.lines(screen, BLACK, True, pointList)
    else:
        image2 = pygame.transform.scale(images[image], (HEX_RADIUS * 2, HEX_RADIUS * 2))
        screen.blit(image2, (x - HEX_RADIUS, y - HEX_RADIUS))
        
def drawBoard(game):
    pointList = [(WIDTH-400, 25), (WIDTH-25, 25), (WIDTH-25, HEIGHT-25), (WIDTH-400, HEIGHT-25)]
    pygame.draw.lines(screen, BLACK, True, pointList)
    
    # render real estate market
    rex = WIDTH - 300
    rey = HEIGHT - 75
    vals = [0, 0, 2, 4, 6, 8, 10]
    text = font.render('Real Estate:', 1, BLACK)
    textpos = text.get_rect(centerx=rex-20, centery=50)
    screen.blit(text, textpos)
    for i in range(7):
        tile = game.getStack()[i]
        drawHex(rex, rey - i * 2.3 * HEX_RADIUS, HEX_RADIUS, tile.getImage(), '')
        text = font.render('+$' + str(vals[i]), 1, BLACK)
        textpos = text.get_rect(centerx=rex - 65, centery=rey - i * 2.3 * HEX_RADIUS)
        screen.blit(text, textpos)
        
    # render basic tiles
    text = font.render('Basic Tiles:', 1, BLACK)
    textpos = text.get_rect(centerx=WIDTH-120, centery=50)
    screen.blit(text, textpos)
    btx = WIDTH - 150
    bty = 110
    drawHex(btx, bty, HEX_RADIUS, game.getCommunityParkTile().getImage(), '')
    text = font.render('x' + str(len(game.getCommunityParkStack())), 1, BLACK)
    textpos = text.get_rect(centerx=btx+HEX_RADIUS*2, centery=bty)
    screen.blit(text, textpos)

    bty = bty + 2.3 * HEX_RADIUS
    drawHex(btx, bty, HEX_RADIUS, game.getHeavyFactoryTile().getImage(), '')
    text = font.render('x' + str(len(game.getHeavyFactoryStack())), 1, BLACK)
    textpos = text.get_rect(centerx=btx+HEX_RADIUS*2, centery=bty)
    screen.blit(text, textpos)
    
    bty = bty + 2.3 * HEX_RADIUS
    drawHex(btx, bty, HEX_RADIUS, game.getSuburbTile().getImage(), '')
    text = font.render('x' + str(len(game.getSuburbStack())), 1, BLACK)
    textpos = text.get_rect(centerx=btx+HEX_RADIUS*2, centery=bty)
    screen.blit(text, textpos)

def drawBigImage(img):
    if img == None:
        return
    img2 = pygame.transform.scale(images[img], (HEX_RADIUS * 6, HEX_RADIUS * 6))
    screen.blit(img2, (287, 0))
    
temp = None
currentState = 0
highlightedTiles = []
removeLater = 0
while not done:
    if (len(game.getStack()) == game.endLength and isEnd == 0):
        isEnd = 1
        print "ENDING TILE DRAWN!"
    
    currentPlayer = players[game.getCurrentPlayer()]
    if (isEnd == 1 and currentPlayer == players[0]):
        isEnd = 2
        print "FINAL ROUND!"
        
    if (isEnd == 2 and currentPlayer == players[1]):
        isEnd = 3
        
    if (isEnd == 3 and currentPlayer == players[0]):
        done = True
        
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif (currentPlayer.getIsHuman() and event.type == pygame.MOUSEBUTTONUP):
            if currentState == 0:
                print pygame.mouse.get_pos()
                temp = currentPlayer.selectTile(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])
                if not temp == None:                   
                    currentState = 1
                    print temp.getID()
                    if int(temp.getID()) > 99:
                        removeLater = 1
                print removeLater

            elif currentState ==1:
                if pygame.mouse.get_pos()[0]<700 and pygame.mouse.get_pos()[0]>600 and pygame.mouse.get_pos()[1]<190 and pygame.mouse.get_pos()[1]>150:
                    print 'laking'
                    newtile = Tile(temp.getID(), 'LAKE', 'None', '', -1, 0, 0, 0, 0, 0, 3, 'M', 'RGCI', 2, "A.jpg")
                    temp = newtile
                else:
                    i = 0
                    for hex in currentPlayer.getHexGrid():
                        if len(highlightedTiles) > 0 and i == highlightedTiles[0]:
                            
                            currentPlayer.takeHumanTurn(temp, i)
                            if removeLater == 1:
                                currentState = 2
                            else:
                                currentState = 0
                                game.update()
                            highlightedTiles = []
                        i= i + 1
            elif currentState == 2:
                print currentState
                v = 0
                while v == 0:
                    v = currentPlayer.tossMe(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])
                    print v
                    print pygame.mouse.get_pos()
                game.update()
                currentState =0
                removeLater = 0
                    
                
        elif (currentPlayer.getIsHuman() and event.type == pygame.MOUSEMOTION and currentState == 1):
            cx, cy = pygame.mouse.get_pos()
            i=0
            for hex in currentPlayer.getHexGrid():
                
                x = HEX_X_START + 1.5 * (i / 7) * HEX_RADIUS
                y = HEX_Y_START + 1.732 * (i % 7) * HEX_RADIUS
                if (i / 7) % 2 != 0:
                    y += HEX_RADIUS * 0.866
                xend = x + HEX_RADIUS
                yend = y + HEX_RADIUS * 3
                x = x - HEX_RADIUS
                y = y + HEX_RADIUS
                i= i + 1
                if(cx>x and cx<xend) and (cy>y and cy<yend) and i in currentPlayer.getValidMoves():
                    highlightedTiles.append(i)
                else:
                    if i in highlightedTiles:
                        highlightedTiles.remove(i)
        
        elif (not currentPlayer.isHuman and event.type == pygame.KEYDOWN):
            currentPlayer.takeTurn()
            game.update()
            
        if (event.type == pygame.MOUSEMOTION):
            big = currentPlayer.getTileWithMouse(pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1])
            if not big == None:
                bigImg = big.getImage()
            else:
                bigImg = None
                
    screen.fill(WHITE)
   
    drawPlayerInfo(players[game.getCurrentPlayer()])
    if currentState == 1:
        currTile = font.render(temp.getName(),1,BLACK)
        curpos = currTile.get_rect(centerx=650, centery=150)
        screen.blit(currTile, curpos)
        lake = font.render('LAKE TILE', 1, BLACK)
        lakepos = lake.get_rect(centerx=650, centery=170)
        screen.blit(lake,lakepos)
    if currentState == 2:
        rem = font.render('Remove a Tile', 1, BLACK)
        rempos = rem.get_rect(centerx=650, centery=150)
        screen.blit(rem, rempos)
    drawBoard(game)
    drawBigImage(bigImg)


    for i in range(len(currentPlayer.getHexGrid())):
        hex = currentPlayer.getHexGrid()[i]
        tile = hex.getTile()
        color = WHITE
        image = ''
        if tile != None:
            image = tile.getImage()
        elif i in currentPlayer.getValidMoves():
            color = (255, 225, 225)
        if len(highlightedTiles) > 0 and highlightedTiles[0] == i:
            color = (255, 0, 0)
        x = HEX_X_START + 1.5 * (i / 7) * HEX_RADIUS
        y = HEX_Y_START + 1.732 * (i % 7) * HEX_RADIUS
        if (i / 7) % 2 != 0:
            y += HEX_RADIUS * 0.866
        drawHex(x, y, HEX_RADIUS, image, color)
    
    pygame.display.flip()
        
players = sorted(players, key=lambda player: player.getPopulation())
print players[len(players)-1].getName(), "wins!"

pygame.quit()
